package com.example.influxdbspring;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import com.influxdb.client.WriteApi;

@RestController
@RequestMapping("/influx")
public class influxdbController {

    // 注入influxDB客户端
    @Autowired
    private InfluxDBClient influxdbClient;

    // 写入数据
    @PostMapping("/post-influx-data")
    public Boolean postInfluxData(@RequestBody Mem mem) {
        mem.setTime(Instant.now());



        // 1、使用 InfluxDB Line Protocol 写入数据
//        String data = "zss,host=host1 used_percent=233";
//        try (WriteApi writeApi = influxdbClient.getWriteApi()) {
//            writeApi.writeRecord("asd", "zcc", WritePrecision.NS, data);
//        }

        // 2.使用 Data Point 写入数据
        Point point = Point
                .measurement("zsn")
                .addTag("host", "host1")
                .addTag("test", "test1")
                .addTag("zxc", "zxc1")
                .addField("used_percent", "qwe0")
                .addField("used_tsc", "qwe1")
                .time(Instant.now(), WritePrecision.NS);
        try (WriteApi writeApi = influxdbClient.getWriteApi()) {
            writeApi.writePoint("aass3", "zcc", point);
        }



        try (WriteApi writeApi = influxdbClient.getWriteApi()) {
            // 桶 组织，精度，度量
            writeApi.writeMeasurement("aass3", "zcc", WritePrecision.NS, mem);
            System.out.println("dfgdgfdfgdgdgdf");
        }
        return Boolean.TRUE;
    }

    // 获取数据
    @GetMapping("/get-influx-data")
    public List<FluxRecord> getInfluxData(@RequestParam Integer startTime) {
        String query = "from(bucket: \"pingao\") |> range(start: -"+startTime+"h) |> filter(fn: (r) => r._measurement == \"mem\")";
        List<FluxTable> tables = influxdbClient.getQueryApi().query(query, "jenson");
        List<FluxRecord> fluxRecords = new ArrayList<>();
        tables.forEach(fluxTable -> {
            List<FluxRecord> records = fluxTable.getRecords();
            fluxRecords.addAll(records);
        });
        return fluxRecords;
    }
}
